<template>
    <el-dialog v-model="props.show" width="900" :before-close="showDialog">
        <el-upload v-model:file-list="fileList" class="upload-demo" :http-request="fileUpLoad" :headers="headers"
            multiple :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="3"
            :on-exceed="handleExceed" :disabled="isDisabled">
            <el-button type="primary" @click="isDisabled = false">上传文件</el-button>
            <a @click="isDisabled = true" href="../../public/resources/用例模版.xlsx" download>下载模板</a>
            <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500KB.
                </div>
            </template>
        </el-upload>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { testCaseImportService } from '@/api/testCaseAPI'

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    caseData: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['close'])
const headers = ref({
    'Authorization': localStorage.getItem('token')
})
const isDisabled = ref(false);

const fileList = ref<UploadUserFile[]>([
    {
        name: 'element-plus-logo.svg',
        url: 'https://element-plus.org/images/element-plus-logo.svg',
    },
    {
        name: 'element-plus-logo2.svg',
        url: 'https://element-plus.org/images/element-plus-logo.svg',
    },
])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile);
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
    )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}

const fileUpLoad = async () => {
    const formData = new FormData();
    formData.set('file', fileList.value[2].raw);
    testCaseImportService(formData)
    emit('close');
}

const showDialog = () => {
    emit('close');
}
</script>